package com.lhc.servlets;

import com.lhc.constant.Constant;
import com.lhc.pojo.ResultVO;
import com.lhc.pojo.User;
import com.lhc.service.UserService;
import com.lhc.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author lhc
 * @version V1.0
 * @date 2021/06/30
 **/
@WebServlet("/user")
public class LoginController extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    public String login(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 收参
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            // 登录
            ResultVO resultVO = userService.login(username, password);
            System.out.println(resultVO);
            if (resultVO.isSuccess()){
                return Constant.REDIRECT + ":/welcome.jsp";

            } else{
                // 登录失败
                return Constant.REDIRECT + ":/index.jsp";
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "服务器正忙，请稍后再试......";
    }
    public String zhuce(HttpServletRequest request, HttpServletResponse response) {
        try {
            //接收参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            //创建cooking对象并赋前端传来的值
            User user = new User();
            BeanUtils.populate(user,parameterMap);
            System.out.println("cooking = " + user);
            //调用业务方法执行上传
            if (userService.findByName(user.getUserName()) == null){
                int i = userService.insert(user);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

        return Constant.REDIRECT + ":/index.jsp";
    }

}